using Sage.Http.Authentication;
using Sage.Http.Core.Handlers;
using Sage.Http.Factory;
using Sage.Http.Models;
using Sage.Http.Utils;
using System.Diagnostics.CodeAnalysis;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;

namespace Sage.Http.Core
{
    /// <summary>
    /// HTTP请求构建器，使用构建者模式实现HTTP请求的流式配置
    /// </summary>
    public class HttpRequestBuilder : IDisposable, IAsyncDisposable
    {
        #region 私有字段

        private readonly HttpRequestMessage _request = new(); // 内部HTTP请求消息
        private readonly HttpRequestManager _manager; // 维护对 HttpRequestManager 的引用
        private readonly Dictionary<string, object> _queryParams = []; // 查询参数

        // 内部处理器组件 - 实现职责分离
        private readonly RequestContentHandler _contentHandler = new();
        private readonly RequestAuthHandler _authHandler = new();
        private readonly RequestConfigHandler _configHandler;

        private bool _disposed = false; // 资源释放标志

        #endregion

        #region 构造函数

        /// <summary>
        /// 初始化HTTP请求构建器实例
        /// </summary>
        /// <param name="manager">HTTP请求管理器</param>
        /// <param name="method">HTTP方法</param>
        /// <param name="url">请求URL</param>
        /// <exception cref="ArgumentNullException">当参数为null或空时抛出</exception>
        /// <exception cref="InvalidOperationException">当URL无法解析时抛出</exception>
        public HttpRequestBuilder(HttpRequestManager manager, HttpMethod method, string url)
        {
            _manager = manager ?? throw new ArgumentNullException(nameof(manager));
            _request.Method = method ?? throw new ArgumentNullException(nameof(method));
            _configHandler = new RequestConfigHandler(_request);

            if (string.IsNullOrEmpty(url))
                throw new ArgumentNullException(nameof(url));

            Uri? baseUri = _manager.BaseAddress;

            bool isUriCreated;
            Uri? requestUri;

            if (baseUri != null)
            {
                // 尝试使用 BaseAddress 和 url 创建 Uri
                isUriCreated = Uri.TryCreate(baseUri, url, out requestUri);
            }
            else
            {
                // 尝试直接创建 Uri，url 必须是绝对地址
                isUriCreated = Uri.TryCreate(url, UriKind.Absolute, out requestUri);
            }

            if (!isUriCreated || requestUri == null)
            {
                throw new InvalidOperationException($"无法解析请求的 URL：'{url}'");
            }

            _request.RequestUri = requestUri;
        }

        #endregion

        #region 内容设置

        /// <summary>
        /// 直接设置HTTP内容
        /// </summary>
        /// <param name="content">HTTP内容对象</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">当content为null时抛出</exception>
        public HttpRequestBuilder WithContent(HttpContent content)
        {
            ThrowIfDisposed();
            _contentHandler.SetContent(content);
            return this;
        }

        #endregion

        #region 资源释放

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// 异步释放资源
        /// </summary>
        /// <returns>表示异步释放操作的任务</returns>
        public async ValueTask DisposeAsync()
        {
            if (_disposed)
                return;

            _disposed = true;

            // 异步释放文件参数
            foreach (var file in _contentHandler.Files)
            {
                try
                {
                    if (file is IAsyncDisposable asyncFile)
                        await asyncFile.DisposeAsync().ConfigureAwait(false);
                    else
                        file?.Dispose();
                }
                catch (Exception ex)
                {
                    // 记录文件参数释放异常，但不中断其他资源的释放
                    System.Diagnostics.Debug.WriteLine($"释放文件参数时发生异常: {ex.Message}");
                }
            }
            _contentHandler.Clear();

            // 异步释放HttpContent
            try
            {
                if (_contentHandler.Content is IAsyncDisposable asyncContent)
                    await asyncContent.DisposeAsync().ConfigureAwait(false);
                else
                    _contentHandler.Content?.Dispose();
            }
            catch (Exception ex)
            {
                // 记录HttpContent释放异常，但不中断其他资源的释放
                System.Diagnostics.Debug.WriteLine($"释放HttpContent时发生异常: {ex.Message}");
            }

            // 释放请求消息
            try
            {
                _request?.Dispose();
            }
            catch (Exception ex)
            {
                // 记录HttpRequestMessage释放异常
                System.Diagnostics.Debug.WriteLine($"释放HttpRequestMessage时发生异常: {ex.Message}");
            }

            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// 释放托管和非托管资源
        /// </summary>
        /// <param name="disposing">是否释放托管资源</param>
        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
                return;

            if (disposing)
            {
                // 释放 FileParameter 资源
                foreach (var file in _contentHandler.Files)
                {
                    try
                    {
                        file?.Dispose();
                    }
                    catch (Exception ex)
                    {
                        // 记录但不抛出异常，避免在 Dispose 中导致更多问题
                        System.Diagnostics.Debug.WriteLine($"释放文件参数时出错: {ex.Message}");
                    }
                }
                _contentHandler.Clear();

                // 释放 HttpContent
                try
                {
                    _contentHandler.Content?.Dispose();
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"释放HttpContent时出错: {ex.Message}");
                }

                // 释放 HttpRequestMessage
                try
                {
                    _request?.Dispose();
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"释放请求消息时出错: {ex.Message}");
                }
            }

            _disposed = true;
        }

        /// <summary>
        /// 检查对象是否已被释放
        /// </summary>
        /// <exception cref="ObjectDisposedException">当对象已被释放时抛出</exception>
        private void ThrowIfDisposed()
        {
            ObjectDisposedException.ThrowIf(_disposed, this);
        }

        #endregion

        #region 请求头配置

        /// <summary>
        /// 配置请求头
        /// </summary>
        /// <param name="name">头部名称</param>
        /// <param name="value">头部值</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        public HttpRequestBuilder WithHeader(string name, string value)
        {
            ThrowIfDisposed();
            _request.Headers.TryAddWithoutValidation(name, value);
            return this;
        }

        /// <summary>
        /// 配置多个请求头
        /// </summary>
        /// <param name="headers">请求头字典</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">当headers为null时抛出</exception>
        public HttpRequestBuilder WithHeaders(IDictionary<string, string> headers)
        {
            ThrowIfDisposed();
            ArgumentNullException.ThrowIfNull(headers);

            foreach (var header in headers)
            {
                WithHeader(header.Key, header.Value);
            }
            return this;
        }

        /// <summary>
        /// 配置Content-Type头
        /// </summary>
        /// <param name="mediaType">媒体类型</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        public HttpRequestBuilder WithContentType(string mediaType)
        {
            ThrowIfDisposed();
            return WithHeader("Content-Type", mediaType);
        }

        /// <summary>
        /// 配置User-Agent头
        /// </summary>
        /// <param name="userAgent">用户代理字符串</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        public HttpRequestBuilder WithUserAgent(string userAgent)
        {
            ThrowIfDisposed();
            return WithHeader("User-Agent", userAgent);
        }

        /// <summary>
        /// 配置Authorization头
        /// </summary>
        /// <param name="value">认证值</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        public HttpRequestBuilder WithAuthorization(string value)
        {
            ThrowIfDisposed();
            return WithHeader("Authorization", value);
        }

        /// <summary>
        /// 配置Bearer Token认证
        /// </summary>
        /// <param name="token">Bearer令牌</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        public HttpRequestBuilder WithBearerToken(string token)
        {
            ThrowIfDisposed();
            return WithHeader("Authorization", $"Bearer {token}");
        }

        /// <summary>
        /// 配置基本认证
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        public HttpRequestBuilder WithBasicAuth(string username, string password)
        {
            ThrowIfDisposed();
            var credentials = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{username}:{password}"));
            return WithHeader("Authorization", $"Basic {credentials}");
        }

        /// <summary>
        /// 配置Accept头为JSON
        /// </summary>
        /// <returns>当前构建器实例，用于链式调用</returns>
        public HttpRequestBuilder AcceptJson()
        {
            ThrowIfDisposed();
            return WithHeader("Accept", "application/json");
        }

        /// <summary>
        /// 配置Accept头为XML
        /// </summary>
        /// <returns>当前构建器实例，用于链式调用</returns>
        public HttpRequestBuilder AcceptXml()
        {
            ThrowIfDisposed();
            return WithHeader("Accept", "application/xml");
        }

        #region 过时的方法 - 请求头

        /// <summary>
        /// 添加请求头
        /// </summary>
        /// <param name="name">头部名称</param>
        /// <param name="value">头部值</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        [Obsolete("使用 WithHeader 方法代替", false)]
        public HttpRequestBuilder AddHeader(string name, string value) => WithHeader(name, value);

        /// <summary>
        /// 添加多个请求头
        /// </summary>
        /// <param name="headers">请求头字典</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">当headers为null时抛出</exception>
        [Obsolete("使用 WithHeaders 方法代替", false)]
        public HttpRequestBuilder AddHeaders(IDictionary<string, string> headers) => WithHeaders(headers);

        #endregion

        #endregion

        #region 查询参数配置

        /// <summary>
        /// 配置查询参数
        /// </summary>
        /// <param name="name">参数名</param>
        /// <param name="value">参数值</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">当name为null或空时抛出</exception>
        public HttpRequestBuilder WithQuery(string name, object value)
        {
            ThrowIfDisposed();
            if (string.IsNullOrEmpty(name))
                throw new ArgumentNullException(nameof(name));

            _queryParams[name] = value;
            return this;
        }

        /// <summary>
        /// 配置多个查询参数
        /// </summary>
        /// <param name="parameters">查询参数字典</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">当parameters为null时抛出</exception>
        public HttpRequestBuilder WithQueries(IDictionary<string, object> parameters)
        {
            ThrowIfDisposed();
            ArgumentNullException.ThrowIfNull(parameters);

            foreach (var param in parameters)
            {
                WithQuery(param.Key, param.Value);
            }
            return this;
        }
        /// <summary>
        /// 配置多个查询参数（使用匿名对象 - 非 AOT 兼容）
        /// </summary>
        /// <param name="queryObject">包含查询参数的匿名对象</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">当queryObject为null时抛出</exception>
        /// <remarks>此方法在 AOT 编译环境中可能无法正常工作，推荐使用其他重载方法</remarks>
        [RequiresUnreferencedCode("使用反射访问对象属性，在 AOT 环境中可能无法正常工作")]
        [RequiresDynamicCode("使用反射访问对象属性，在 AOT 环境中可能无法正常工作")]
        public HttpRequestBuilder WithQueries(object queryObject)
        {
            ThrowIfDisposed();
            ArgumentNullException.ThrowIfNull(queryObject);
            var properties = queryObject.GetType().GetProperties();
            foreach (var prop in properties)
            {
                var value = prop.GetValue(queryObject);
                if (value != null)
                {
                    WithQuery(prop.Name, value);
                }
            }
            return this;
        }

        /// <summary>
        /// 配置多个查询参数（使用键值对参数）
        /// </summary>
        /// <param name="parameters">查询参数的键值对</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        public HttpRequestBuilder WithQueries(params (string name, object value)[] parameters)
        {
            ThrowIfDisposed();
            ArgumentNullException.ThrowIfNull(parameters);

            foreach (var (name, value) in parameters)
            {
                WithQuery(name, value);
            }
            return this;
        }

        /// <summary>
        /// 简化的查询参数配置方法（别名）
        /// </summary>
        /// <param name="name">参数名</param>
        /// <param name="value">参数值</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        public HttpRequestBuilder Query(string name, object value) => WithQuery(name, value);

        #region 过时的方法 - 查询参数

        /// <summary>
        /// 添加查询参数
        /// </summary>
        /// <param name="name">参数名</param>
        /// <param name="value">参数值</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">当name为null或空时抛出</exception>
        [Obsolete("使用 WithQuery 方法代替", false)]
        public HttpRequestBuilder AddQueryParameter(string name, object value) => WithQuery(name, value);

        /// <summary>
        /// 批量添加查询参数
        /// </summary>
        /// <param name="queryParams">查询参数字典</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">当queryParams为null时抛出</exception>
        [Obsolete("使用 WithQueries 方法代替", false)]
        public HttpRequestBuilder AddQueryParameter(Dictionary<string, object> queryParams) => WithQueries(queryParams);

        /// <summary>
        /// 添加多个查询参数
        /// </summary>
        /// <param name="parameters">查询参数字典</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">当parameters为null时抛出</exception>
        [Obsolete("使用 WithQueries 方法代替", false)]
        public HttpRequestBuilder AddQueryParameters(IDictionary<string, object> parameters) => WithQueries(parameters);

        #endregion

        #endregion

        #region 请求体配置

        /// <summary>
        /// 设置请求体内容
        /// </summary>
        /// <param name="body">请求体内容</param>
        /// <param name="bodyType">内容类型</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        public HttpRequestBuilder WithBody(string body, BodyType bodyType)
        {
            ThrowIfDisposed();
            _contentHandler.SetBody(body, bodyType);
            return this;
        }

        /// <summary>
        /// 设置请求体内容（字典版本）
        /// </summary>
        /// <param name="data">要转换的字典数据</param>
        /// <param name="bodyType">内容类型</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">当data为null时抛出</exception>
        /// <exception cref="ArgumentException">当bodyType不支持字典转换时抛出</exception>
        public HttpRequestBuilder WithBody(IDictionary<string, object> data, BodyType bodyType)
        {
            ThrowIfDisposed();
            ArgumentNullException.ThrowIfNull(data);

            string convertedBody = DictionaryConverter.ConvertToString(data, bodyType);
            return WithBody(convertedBody, bodyType);
        }

        /// <summary>
        /// 设置请求体内容（字典版本，默认为JSON格式）
        /// </summary>
        /// <param name="data">要转换的字典数据</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">当data为null时抛出</exception>
        public HttpRequestBuilder WithBody(IDictionary<string, object> data)
        {
            return WithBody(data, BodyType.Json);
        }

        /// <summary>
        /// 配置JSON内容（AOT兼容版本）
        /// </summary>
        /// <typeparam name="T">内容类型</typeparam>
        /// <param name="value">要序列化为JSON的对象</param>
        /// <param name="jsonTypeInfo">JSON类型信息，用于AOT环境</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">当value或jsonTypeInfo为null时抛出</exception>
        public HttpRequestBuilder WithJsonContent<T>(T value, JsonTypeInfo<T> jsonTypeInfo)
        {
            ThrowIfDisposed();
            ArgumentNullException.ThrowIfNull(value);
            ArgumentNullException.ThrowIfNull(jsonTypeInfo);

            string json = JsonSerializer.Serialize(value, jsonTypeInfo);
            return WithBody(json, BodyType.Json);
        }

        /// <summary>
        /// 配置JSON内容（非AOT兼容版本）
        /// </summary>
        /// <typeparam name="T">内容类型</typeparam>
        /// <param name="value">要序列化为JSON的对象</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">当value为null时抛出</exception>
        [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")]
        [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")]
        [Obsolete("此方法在AOT环境中不安全，请使用带有JsonTypeInfo参数的WithJsonContent方法")]
        public HttpRequestBuilder WithJsonContent<T>(T value)
        {
            ThrowIfDisposed();
            ArgumentNullException.ThrowIfNull(value);

            string json = JsonSerializer.Serialize(value);
            return WithBody(json, BodyType.Json);
        }

        /// <summary>
        /// 配置JSON内容
        /// </summary>
        /// <typeparam name="T">内容类型</typeparam>
        /// <param name="value">要序列化为JSON的对象</param>
        /// <param name="options">JSON序列化选项</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">当value或options为null时抛出</exception>
        [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")]
        [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")]
        [Obsolete("此方法在AOT环境中不安全，请使用带有JsonTypeInfo参数的WithJsonContent方法")]
        public HttpRequestBuilder WithJsonContent<T>(T value, JsonSerializerOptions options)
        {
            ThrowIfDisposed();
            ArgumentNullException.ThrowIfNull(value);
            ArgumentNullException.ThrowIfNull(options);

            string json = JsonSerializer.Serialize(value, options);
            return WithBody(json, BodyType.Json);
        }

        /// <summary>
        /// 配置JSON内容的简化版本
        /// </summary>
        /// <typeparam name="T">内容类型</typeparam>
        /// <param name="value">要序列化为JSON的对象</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")]
        [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")]
        public HttpRequestBuilder WithJson<T>(T value) => WithJsonContent(value);

        /// <summary>
        /// 配置JSON内容字符串
        /// </summary>
        /// <param name="jsonContent">JSON内容字符串</param>
        /// <param name="bodyType">内容类型，默认为JSON</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        public HttpRequestBuilder WithJsonContent(string jsonContent, BodyType bodyType = BodyType.Json)
        {
            ThrowIfDisposed();
            return WithBody(jsonContent, bodyType);
        }
        
        /// <summary>
        /// 配置XML内容
        /// </summary>
        /// <param name="xmlContent">XML内容字符串</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        public HttpRequestBuilder WithXmlContent(string xmlContent)
        {
            ThrowIfDisposed();
            return WithBody(xmlContent, BodyType.Xml);
        }

        /// <summary>
        /// 配置纯文本内容
        /// </summary>
        /// <param name="textContent">文本内容</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        public HttpRequestBuilder WithTextContent(string textContent)
        {
            ThrowIfDisposed();
            return WithBody(textContent, BodyType.Text);
        }

        #region 过时的方法 - 请求体

        /// <summary>
        /// 设置请求体内容
        /// </summary>
        /// <param name="body">请求体内容</param>
        /// <param name="bodyType">内容类型</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        [Obsolete("使用 WithBody 方法代替", false)]
        public HttpRequestBuilder SetBody(string body, BodyType bodyType) => WithBody(body, bodyType);

        #endregion

        #endregion

        #region 表单和文件配置

        /// <summary>
        /// 添加表单字段
        /// </summary>
        /// <param name="name">字段名</param>
        /// <param name="value">字段值</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">当name或value为null时抛出</exception>
        public HttpRequestBuilder AddFormField(string name, string value)
        {
            ThrowIfDisposed();
            ArgumentNullException.ThrowIfNull(name);
            ArgumentNullException.ThrowIfNull(value);
            _contentHandler.AddFormField(name, value);
            return this;
        }

        /// <summary>
        /// 添加多个表单字段
        /// </summary>
        /// <param name="formData">表单数据字典</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">当formData为null时抛出</exception>
        public HttpRequestBuilder AddFormFields(IDictionary<string, string> formData)
        {
            ThrowIfDisposed();
            ArgumentNullException.ThrowIfNull(formData);

            foreach (var field in formData)
            {
                AddFormField(field.Key, field.Value);
            }
            return this;
        }

        /// <summary>
        /// 添加文件参数
        /// </summary>
        /// <param name="file">文件参数</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">当file为null时抛出</exception>
        public HttpRequestBuilder AddFile(FileParameter file)
        {
            ThrowIfDisposed();
            ArgumentNullException.ThrowIfNull(file);
            _contentHandler.AddFile(file);
            return this;
        }

        /// <summary>
        /// 从文件路径添加文件
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="fieldName">字段名</param>
        /// <param name="contentType">内容类型，如果为null则自动检测</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        public HttpRequestBuilder AddFileFromPath(string filePath, string fieldName = "file", string? contentType = null)
        {
            ThrowIfDisposed();
            ArgumentException.ThrowIfNullOrEmpty(filePath);
            
            if (contentType == null)
            {
                contentType = Extensions.HttpClientBuilderExtensions.GetMimeTypeForFileExtension(Path.GetExtension(filePath));
            }
            
            var file = FileParameter.FromFile(filePath, fieldName, contentType);
            return AddFile(file);
        }

        /// <summary>
        /// 添加多个文件参数
        /// </summary>
        /// <param name="files">文件参数列表</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">当files为null时抛出</exception>
        public HttpRequestBuilder AddFiles(IEnumerable<FileParameter> files)
        {
            ThrowIfDisposed();
            ArgumentNullException.ThrowIfNull(files);

            foreach (var file in files)
            {
                AddFile(file);
            }
            return this;
        }

        #endregion

        #region 认证配置

        /// <summary>
        /// 配置认证提供者
        /// </summary>
        /// <param name="authProvider">认证提供者</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">当authProvider为null时抛出</exception>
        public HttpRequestBuilder WithAuthentication(IAuthenticationProvider authProvider)
        {
            ThrowIfDisposed();
            _authHandler.SetAuthentication(authProvider);
            return this;
        }

        /// <summary>
        /// 配置认证提供者的简化版本
        /// </summary>
        /// <param name="authProvider">认证提供者</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">当authProvider为null时抛出</exception>
        public HttpRequestBuilder WithAuth(IAuthenticationProvider authProvider) => WithAuthentication(authProvider);

        #region 过时的方法 - 认证

        /// <summary>
        /// 添加认证提供者
        /// </summary>
        /// <param name="authProvider">认证提供者</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        /// <exception cref="ArgumentNullException">当authProvider为null时抛出</exception>
        [Obsolete("使用 WithAuthentication 或 WithAuth 方法代替", false)]
        public HttpRequestBuilder AddAuthentication(IAuthenticationProvider authProvider) => WithAuthentication(authProvider);

        #endregion

        #endregion

        #region 请求配置

        /// <summary>
        /// 禁用此请求的日志记录
        /// </summary>
        /// <returns>当前构建器实例，用于链式调用</returns>
        public HttpRequestBuilder DisableLogging()
        {
            ThrowIfDisposed();
            _configHandler.DisableLogging();
            return this;
        }

        /// <summary>
        /// 配置请求超时时间
        /// </summary>
        /// <param name="timeout">超时时间</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        public HttpRequestBuilder WithTimeout(TimeSpan timeout)
        {
            ThrowIfDisposed();
            _configHandler.SetTimeout(timeout);
            return this;
        }

        /// <summary>
        /// 配置超时时间的简化版本
        /// </summary>
        /// <param name="timeout">超时时间</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        public HttpRequestBuilder Timeout(TimeSpan timeout) => WithTimeout(timeout);

        /// <summary>
        /// 配置上传进度报告接口
        /// </summary>
        /// <param name="progress">进度报告接口</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        public HttpRequestBuilder WithProgress(IProgress<float> progress)
        {
            ThrowIfDisposed();
            _configHandler.SetProgress(progress);
            return this;
        }

        /// <summary>
        /// 配置取消令牌
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        public HttpRequestBuilder WithCancellation(CancellationToken cancellationToken)
        {
            ThrowIfDisposed();
            _configHandler.SetCancellationToken(cancellationToken);
            return this;
        }

        #region 过时的方法 - 请求配置

        /// <summary>
        /// 设置请求超时时间
        /// </summary>
        /// <param name="timeout">超时时间</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        [Obsolete("使用 WithTimeout 或 Timeout 方法代替", false)]
        public HttpRequestBuilder SetTimeout(TimeSpan timeout) => WithTimeout(timeout);

        /// <summary>
        /// 设置上传进度报告接口
        /// </summary>
        /// <param name="progress">进度报告接口</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        [Obsolete("使用 WithProgress 方法代替", false)]
        public HttpRequestBuilder SetProgress(IProgress<float> progress) => WithProgress(progress);

        /// <summary>
        /// 设置取消令牌
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>当前构建器实例，用于链式调用</returns>
        [Obsolete("使用 WithCancellation 方法代替", false)]
        public HttpRequestBuilder SetCancellationToken(CancellationToken cancellationToken) => WithCancellation(cancellationToken);

        #endregion

        #endregion

        #region 请求发送

        /// <summary>
        /// 异步发送HTTP请求
        /// </summary>
        /// <param name="cancellationToken">取消令牌（可选）</param>
        /// <returns>HTTP响应消息</returns>
        public async Task<HttpResponseMessage> SendAsync(CancellationToken? cancellationToken = default)
        {
            ThrowIfDisposed();

            // 构建完整的请求 URI，包括查询参数
            if (_queryParams.Count > 0)
            {
                string requestUrl = HttpRequestBuilderFactory.BuildRequestUrl(_request.RequestUri!.ToString(), _queryParams);
                _request.RequestUri = new Uri(requestUrl);
            }

            // 构建请求内容
            _contentHandler.ApplyContent(_request);

            // 添加认证信息
            await _authHandler.ApplyAuthenticationAsync(_request);

            // 使用 HttpRequestManager 发送请求
            return await _manager.SendAsync(_request, cancellationToken ?? _configHandler.CancellationToken);
        }

        /// <summary>
        /// 同步发送HTTP请求
        /// </summary>
        /// <returns>HTTP响应消息</returns>
        public HttpResponseMessage Send()
        {
            ThrowIfDisposed();

            // 构建完整的请求 URI，包括查询参数
            if (_queryParams.Count > 0)
            {
                string requestUrl = HttpRequestBuilderFactory.BuildRequestUrl(_request.RequestUri!.ToString(), _queryParams);
                _request.RequestUri = new Uri(requestUrl);
            }

            // 构建请求内容
            _contentHandler.ApplyContent(_request);

            // 添加认证信息
            _authHandler.ApplyAuthenticationAsync(_request).GetAwaiter().GetResult();

            // 使用 HttpRequestManager 发送请求
            return _manager.Send(_request, _configHandler.CancellationToken);
        }

        /// <summary>
        /// 发送请求并以JSON格式获取响应（使用全局配置，支持AOT）
        /// </summary>
        /// <typeparam name="T">响应类型</typeparam>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>反序列化后的响应对象</returns>
        /// <remarks>
        /// <para>此方法会优先使用全局配置的 JsonSerializerContext（AOT友好），
        /// 如果没有配置全局上下文，则使用全局 JsonSerializerOptions，
        /// 最后回退到默认选项。</para>
        /// 
        /// <para><strong>AOT 环境使用建议：</strong></para>
        /// <list type="bullet">
        /// <item><description>配置全局 JsonSerializerContext 以获得最佳性能和完全 AOT 支持</description></item>
        /// <item><description>使用 JsonSerializerOptionsFactory.SetGlobalContext() 设置全局上下文</description></item>
        /// <item><description>确保响应类型 T 包含在 JsonSerializerContext 中</description></item>
        /// <item><description>当配置了全局 JsonSerializerContext 时，此方法不会产生 AOT 警告</description></item>
        /// </list>
        /// 
        /// <para><strong>示例：</strong></para>
        /// <code>
        /// // 配置全局上下文（通常在应用启动时）
        /// JsonSerializerOptionsFactory.SetGlobalContext(MyJsonContext.Default);
        /// 
        /// // 使用时不会产生 AOT 警告
        /// var result = await httpRequest.CreateRequest(route)
        ///     .SendAsJsonAsync&lt;MyResponseType&gt;(cancellationToken);
        /// </code>
        /// </remarks>
        [UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "When global JsonSerializerContext is configured, this method uses AOT-friendly deserialization.")]
        [UnconditionalSuppressMessage("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.", Justification = "When global JsonSerializerContext is configured, this method uses AOT-friendly deserialization.")]
        [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed when JsonSerializerContext is not configured.")]
        [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation when JsonSerializerContext is not configured.")]
        public async Task<T?> SendAsJsonAsync<T>(CancellationToken cancellationToken = default)
        {
            ThrowIfDisposed();
            using var response = await SendAsync(cancellationToken).ConfigureAwait(false);
            response.EnsureSuccessStatusCode();

            var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);

            // 优先尝试使用全局配置的 JsonSerializerContext（AOT友好）
            var globalContext = JsonSerializerOptionsFactory.GetGlobalContext();
            if (globalContext != null)
            {
                // 尝试从全局上下文中获取类型信息
                var typeInfo = globalContext.GetTypeInfo(typeof(T));
                if (typeInfo is JsonTypeInfo<T> jsonTypeInfo)
                {
                    return await JsonSerializer.DeserializeAsync(stream, jsonTypeInfo, cancellationToken).ConfigureAwait(false);
                }
            }

            // 如果没有全局上下文或类型信息不匹配，使用全局选项
            var effectiveOptions = JsonSerializerOptionsFactory.GetEffectiveOptions();
            return await JsonSerializer.DeserializeAsync<T>(stream, effectiveOptions, cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// 发送请求并以JSON格式获取响应（AOT兼容版本）
        /// </summary>
        /// <typeparam name="T">响应类型</typeparam>
        /// <param name="jsonTypeInfo">JSON类型信息，用于AOT环境</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>反序列化后的响应对象</returns>
        /// <exception cref="ArgumentNullException">当jsonTypeInfo为null时抛出</exception>
        public async Task<T?> SendAsJsonAsync<T>(
            JsonTypeInfo<T> jsonTypeInfo,
            CancellationToken cancellationToken = default)
        {
            ThrowIfDisposed();
            ArgumentNullException.ThrowIfNull(jsonTypeInfo);

            using var response = await SendAsync(cancellationToken).ConfigureAwait(false);
            response.EnsureSuccessStatusCode();

            var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
            return await JsonSerializer.DeserializeAsync(stream, jsonTypeInfo, cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// 发送请求并以JSON格式获取响应（使用自定义选项）
        /// </summary>
        /// <typeparam name="T">响应类型</typeparam>
        /// <param name="options">JSON序列化选项</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>反序列化后的响应对象</returns>
        /// <exception cref="ArgumentNullException">当options为null时抛出</exception>
        [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")]
        [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")]
        public async Task<T?> SendAsJsonAsync<T>(
            JsonSerializerOptions options,
            CancellationToken cancellationToken = default)
        {
            ThrowIfDisposed();
            ArgumentNullException.ThrowIfNull(options);

            using var response = await SendAsync(cancellationToken).ConfigureAwait(false);
            response.EnsureSuccessStatusCode();

            var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
            return await JsonSerializer.DeserializeAsync<T>(stream, options, cancellationToken).ConfigureAwait(false);
        }

        #region 过时的方法 - 请求发送

        /// <summary>
        /// 发送请求并反序列化响应为指定类型（非AOT兼容版本）
        /// </summary>
        /// <typeparam name="T">响应类型</typeparam>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>反序列化后的响应对象</returns>
        [Obsolete("使用 SendAsJsonAsync 方法代替", false)]
        [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")]
        [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")]
        public async Task<T?> SendAndDeserializeAsync<T>(CancellationToken cancellationToken = default)
            => await SendAsJsonAsync<T>(cancellationToken);

        /// <summary>
        /// 发送请求并反序列化响应为指定类型（AOT兼容版本）
        /// </summary>
        /// <typeparam name="T">响应类型</typeparam>
        /// <param name="jsonTypeInfo">JSON类型信息，用于AOT环境</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>反序列化后的响应对象</returns>
        /// <exception cref="ArgumentNullException">当jsonTypeInfo为null时抛出</exception>
        [Obsolete("使用 SendAsJsonAsync 方法代替", false)]
        public async Task<T?> SendAndDeserializeAsync<T>(
            JsonTypeInfo<T> jsonTypeInfo,
            CancellationToken cancellationToken = default)
            => await SendAsJsonAsync(jsonTypeInfo, cancellationToken);

        /// <summary>
        /// 发送请求并反序列化响应为指定类型
        /// </summary>
        /// <typeparam name="T">响应类型</typeparam>
        /// <param name="options">JSON序列化选项</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>反序列化后的响应对象</returns>
        /// <exception cref="ArgumentNullException">当options为null时抛出</exception>
        [Obsolete("使用 SendAsJsonAsync 方法代替", false)]
        [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")]
        [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")]
        public async Task<T?> SendAndDeserializeAsync<T>(
            JsonSerializerOptions options,
            CancellationToken cancellationToken = default)
            => await SendAsJsonAsync<T>(options, cancellationToken);

        #endregion

        #endregion

        #region 流式API支持

        /// <summary>
        /// 异步发送 HTTP 请求并作为异步枚举器获取流式响应（AOT 兼容版本）
        /// </summary>
        /// <typeparam name="T">响应项类型</typeparam>
        /// <param name="jsonTypeInfo">JSON 类型信息，用于 AOT 环境</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>响应项的异步枚举器</returns>
        /// <exception cref="ArgumentNullException">当jsonTypeInfo为null时抛出</exception>
        public async IAsyncEnumerable<T> SendAsStream<T>(
            JsonTypeInfo<T> jsonTypeInfo,
            [EnumeratorCancellation] CancellationToken cancellationToken = default)
        {
            ArgumentNullException.ThrowIfNull(jsonTypeInfo);

            // 构建完整的请求 URI，包括查询参数
            if (_queryParams.Count > 0)
            {
                string requestUrl = HttpRequestBuilderFactory.BuildRequestUrl(_request.RequestUri!.ToString(), _queryParams);
                _request.RequestUri = new Uri(requestUrl);
            }

            // 构建请求内容
            _contentHandler.ApplyContent(_request, cancellationToken: cancellationToken);

            // 添加认证信息
            _authHandler.ApplyAuthenticationAsync(_request).GetAwaiter().GetResult();

            // 使用 HttpRequestManager 发送请求并获取流式响应
            await foreach (var item in _manager.SendAsStream(_request, jsonTypeInfo, cancellationToken))
            {
                yield return item;
            }
        }

        /// <summary>
        /// 异步发送HTTP请求并作为异步枚举器获取流式响应
        /// </summary>
        /// <typeparam name="T">响应项类型</typeparam>
        /// <param name="deserializer">自定义反序列化函数，如果为null则自动创建</param>
        /// <param name="jsonTypeInfo">JSON类型信息，用于AOT环境（推荐）</param>
        /// <param name="jsonOptions">自定义JSON序列化选项</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>响应项的异步枚举器</returns>
        /// <remarks>
        /// 在AOT环境中，建议提供jsonTypeInfo参数以启用源生成序列化。
        /// </remarks>
        [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")]
        [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation.")]
        public async IAsyncEnumerable<T> SendAsStreamAsync<T>(
            Func<string, T>? deserializer = null,
            JsonTypeInfo<T>? jsonTypeInfo = null,
            JsonSerializerOptions? jsonOptions = null,
            [EnumeratorCancellation] CancellationToken cancellationToken = default)
        {
            // 构建完整的请求URI和内容
            if (_queryParams.Count > 0)
            {
                string requestUrl = HttpRequestBuilderFactory.BuildRequestUrl(_request.RequestUri!.ToString(), _queryParams);
                _request.RequestUri = new Uri(requestUrl);
            }

            _contentHandler.ApplyContent(_request, cancellationToken: cancellationToken);
            _request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream"));

            // 合并取消令牌
            using var combinedCts = CancellationTokenSource.CreateLinkedTokenSource(_configHandler.CancellationToken, cancellationToken);

            HttpResponseMessage? response = null;
            Stream? stream = null;
            StreamReader? reader = null;

            try
            {
                // 发送请求
                response = await _manager.SendRequestAsync(
                    _request,
                    HttpCompletionOption.ResponseHeadersRead,
                    combinedCts.Token).ConfigureAwait(false);

                response.EnsureSuccessStatusCode();

                // 创建反序列化函数
                deserializer ??= JsonSerializerFactory.CreateDeserializer(jsonTypeInfo, jsonOptions);

                stream = await response.Content.ReadAsStreamAsync(combinedCts.Token).ConfigureAwait(false);
                reader = new StreamReader(stream);

                string? line;
                while ((line = await reader.ReadLineAsync(combinedCts.Token).ConfigureAwait(false)) != null)
                {
                    combinedCts.Token.ThrowIfCancellationRequested();

                    // 跳过空行
                    if (string.IsNullOrWhiteSpace(line))
                        continue;

                    // 提取并处理数据行
                    string dataContent = ExtractDataContent(line);
                    if (string.IsNullOrEmpty(dataContent))
                        continue;

                    // 处理数据行
                    if (JsonSerializerFactory.TryDeserialize(dataContent, deserializer, out T? item) &&
                        item is not null)
                    {
                        yield return item;
                    }
                }
            }
            finally
            {
                reader?.Dispose();
                stream?.Dispose();
                response?.Dispose();
            }
        }

        /// <summary>
        /// 发送请求并支持流式下载，报告进度
        /// </summary>
        /// <param name="destination">目标流</param>
        /// <param name="progress">进度报告接口</param>
        /// <param name="bufferSize">缓冲区大小，默认81920字节(80KB)</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>下载的总字节数</returns>
        /// <exception cref="ArgumentNullException">当destination为null时抛出</exception>
        /// <exception cref="ArgumentException">当目标流不可写时抛出</exception>
        /// <exception cref="HttpRequestException">当下载请求失败时抛出</exception>
        public async Task<long> DownloadToStreamAsync(
            Stream destination,
            IProgress<float>? progress = null,
            int bufferSize = 81920,
            CancellationToken cancellationToken = default)
        {
            ArgumentNullException.ThrowIfNull(destination);

            if (!destination.CanWrite)
                throw new ArgumentException("目标流必须可写", nameof(destination));

            // 构建完整的请求 URI，包括查询参数
            if (_queryParams.Count > 0)
            {
                string requestUrl = HttpRequestBuilderFactory.BuildRequestUrl(_request.RequestUri!.ToString(), _queryParams);
                _request.RequestUri = new Uri(requestUrl);
            }

            // 构建请求内容
            _contentHandler.ApplyContent(_request, _configHandler.Progress, _configHandler.CancellationToken);

            // 合并取消令牌
            using var combinedCts = CancellationTokenSource.CreateLinkedTokenSource(_configHandler.CancellationToken, cancellationToken);

            // 使用ResponseHeadersRead选项，以便在接收到头信息后就返回响应
            HttpResponseMessage response;
            try
            {
                response = await _manager.SendRequestAsync(
                    _request,
                    HttpCompletionOption.ResponseHeadersRead,
                    combinedCts.Token).ConfigureAwait(false);

                response.EnsureSuccessStatusCode();
            }
            catch (Exception ex)
            {
                throw new HttpRequestException($"下载请求失败: {ex.Message}", ex);
            }

            try
            {
                var contentLength = response.Content.Headers.ContentLength;
                using var contentStream = await response.Content.ReadAsStreamAsync(combinedCts.Token).ConfigureAwait(false);

                var buffer = new byte[bufferSize];
                long totalBytesRead = 0;
                int bytesRead;

                // 报告初始进度
                progress?.Report(0);

                while ((bytesRead = await contentStream.ReadAsync(buffer, combinedCts.Token).ConfigureAwait(false)) > 0)
                {
                    await destination.WriteAsync(buffer.AsMemory(0, bytesRead), combinedCts.Token).ConfigureAwait(false);
                    totalBytesRead += bytesRead;

                    if (progress != null && contentLength.HasValue && contentLength.Value > 0)
                    {
                        var progressValue = (float)totalBytesRead / contentLength.Value;
                        progress.Report(Math.Min(1.0f, progressValue)); // 确保不超过100%
                    }

                    combinedCts.Token.ThrowIfCancellationRequested();
                }

                // 确保最终进度为100%
                progress?.Report(1.0f);

                return totalBytesRead;
            }
            finally
            {
                // 确保响应被释放
                response.Dispose();
            }
        }

        #endregion

        #region 私有辅助方法

        /// <summary>
        /// 提取数据内容，处理SSE格式和普通文本行
        /// </summary>
        /// <param name="line">原始行文本</param>
        /// <returns>数据内容</returns>
        private static string ExtractDataContent(string line)
        {
            // 检查是否为SSE格式的数据行  
            if (line.StartsWith("data:", StringComparison.OrdinalIgnoreCase))
            {
                return line[5..].Trim();
            }

            return line;
        }

        #endregion
    }
}